package com.gy.api.pc.ykz.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.api.request.OapiGettokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiRpcOauth2DingtalkAppTokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiGettokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiRpcOauth2DingtalkAppTokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentPostClient;
import com.gy.api.base.ApiIndex;
import com.gy.api.base.R;
import com.gy.api.base.Type;
import com.gy.api.pc.sys.user.dao.SysUserDao;
import com.gy.api.pc.sys.user.domain.po.SysUserPO;
import com.gy.api.pc.sys.user.domain.vo.UserLoginResVO;
import com.gy.api.pc.ykz.domain.OapiRpcAuth2UserInfo;
import com.gy.api.pc.ykz.domain.YKZBindVO;
import com.gy.api.pc.ykz.domain.YKZLoginResVO;
import com.gy.api.pc.ykz.domain.YKZLoginVO;
import com.gy.api.pc.ykz.service.IntelligentPostService;
import com.gy.exception.BusinessException;
import com.gy.util.RestTemplateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;

@Controller
@RequestMapping("/ykz")
@Api( tags = ApiIndex.YKZController)
@Log4j2
public class YKZController {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private IntelligentPostService intelligentPostService;
//
//    @ApiOperation(value = "愉快政授权登陆(返回token代表登陆成功)")
//    @PostMapping(value = "/login")
//    @ResponseBody
//    public R<YKZLoginResVO> login(@ApiParam(value = "查询参数") @Valid @RequestBody YKZLoginVO userLogin, BindingResult bindingResult) {
//        String ykzToken = intelligentPostService.getToken();
//        // 渝快政登录请求带过来的code
//        String authCode = userLogin.getAuthCode();
//        OapiRpcAuth2UserInfo userInfo = intelligentPostService.getUserInfo(authCode, ykzToken);
//        if (userInfo == null) {
//            throw new BusinessException(Type.FAIL.getCode(),authCode + ", 用户不存在");
//        }
//        String accountId = userInfo.getAccountId().toString();
//
//        Example example=new Example(SysUserPO.class);
//        example.and().andEqualTo("ykzId",accountId);
//        SysUserPO sysUserPO=sysUserDao.selectOneByExample(example);
//
//        YKZLoginResVO userLoginResVO =new YKZLoginResVO();
//        userLoginResVO.setYkzId(accountId);
//        if(sysUserPO!=null){
//            StpUtil.login(sysUserPO.getId(),"pc");;
//            userLoginResVO.setId(sysUserPO.getId());
//            userLoginResVO.setToken(StpUtil.getTokenValue());
//            userLoginResVO.setIsAdmin(2);
//            if(sysUserPO.getLoginName().equals("admin")){
//                userLoginResVO.setIsAdmin(1);
//            }
//            userLoginResVO.setUserName(sysUserPO.getUserName());
//        }
//        return new R().setData(userLoginResVO);
//    }

    private String url="http://100.190.0.112:8182/api/ykz/get_user_info";

    @ApiOperation(value = "愉快政授权登陆(返回token代表登陆成功)")
    @PostMapping(value = "/login")
    @ResponseBody
    public R<YKZLoginResVO> login(@ApiParam(value = "查询参数") @Valid @RequestBody YKZLoginVO userLogin, BindingResult bindingResult) {
//        String ykzToken = intelligentPostService.getToken();
//         渝快政登录请求带过来的code
        String authCode = userLogin.getAuthCode();

        ResponseEntity responseEntity=RestTemplateUtils.get(url+"?authCode="+authCode,JSONObject.class);
        JSONObject jsonObject= (JSONObject) responseEntity.getBody();

        log.info("responseEntity:::::::::::::"+responseEntity.toString());
        log.info("body:::::::::::::"+jsonObject.toJSONString());
        OapiRpcAuth2UserInfo userInfo=jsonObject.getObject("data",OapiRpcAuth2UserInfo.class);
//        OapiRpcAuth2UserInfo userInfo = intelligentPostService.getUserInfo(authCode, ykzToken);
        if (userInfo == null) {
            throw new BusinessException(Type.FAIL.getCode(),authCode + ", 用户不存在");
        }
        String accountId = userInfo.getAccountId().toString();

        Example example=new Example(SysUserPO.class);
        example.and().andEqualTo("ykzId",accountId);
        SysUserPO sysUserPO=sysUserDao.selectOneByExample(example);

        YKZLoginResVO userLoginResVO =new YKZLoginResVO();
        userLoginResVO.setYkzId(accountId);
        if(sysUserPO!=null){
            StpUtil.login(sysUserPO.getId(),"pc");;
            userLoginResVO.setId(sysUserPO.getId());
            userLoginResVO.setToken(StpUtil.getTokenValue());
            userLoginResVO.setIsAdmin(2);
            if(sysUserPO.getLoginName().equals("admin")){
                userLoginResVO.setIsAdmin(1);
            }
            userLoginResVO.setUserName(sysUserPO.getUserName());
        }
        return new R().setData(userLoginResVO);
    }



    @ApiOperation(value = "愉快政绑定系统用户")
    @PostMapping(value = "/bind")
    @ResponseBody
    @SaCheckLogin
    public R bind(@ApiParam(value = "查询参数") @Valid @RequestBody YKZBindVO bindVO, BindingResult bindingResult) {
        SysUserPO sysUserPO=null;
        if(StringUtils.isBlank(bindVO.getUserId())){
            sysUserPO=sysUserDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
        }else{
            sysUserPO=sysUserDao.selectByPrimaryKey(bindVO.getUserId());
        }
        Example example=new Example(SysUserPO.class);
        example.and().andEqualTo("ykzId",bindVO.getYkzId());
        SysUserPO sysOldUserPO=sysUserDao.selectOneByExample(example);
        if(sysOldUserPO!=null){
            throw new BusinessException(Type.FAIL.getCode(), "愉快政用户已经关联系统用户，请勿重复绑定");
        }
        sysUserPO.setYkzId(bindVO.getYkzId());
        sysUserPO.preUpdate();
        sysUserDao.updateByPrimaryKeySelective(sysUserPO);
        return new R();
    }



}
